package org.insatandroidclub.animalsforkids;

import java.util.List;

import org.insatandroidclub.animalsforkids.model.Animal;
import org.insatandroidclub.animalsforkids.utils.AnimalsDB;
import org.insatandroidclub.animalsforkids.utils.MiscFunctions;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class GameActivity extends Activity implements OnClickListener, OnCompletionListener {

	private ImageView gameCurrentAnimalImageView;
	private Button gameChoice1Button;
	private Button gameChoice2Button;
	private Button gameChoice3Button;
	private AnimalsDB animalsDB;
	private List<Animal> animalsCarousel;
	private int currentIndex = 0;
	private boolean fromgoodanswer = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game);
		gameCurrentAnimalImageView = (ImageView)findViewById(R.id.game_currentanimal_imageview);
		gameChoice1Button = (Button)findViewById(R.id.game_choice1_button);
		gameChoice2Button = (Button)findViewById(R.id.game_choice2_button);
		gameChoice3Button = (Button)findViewById(R.id.game_choice3_button);
		gameChoice1Button.setOnClickListener(this);
		gameChoice2Button.setOnClickListener(this);
		gameChoice3Button.setOnClickListener(this);
		animalsDB = new AnimalsDB();
		animalsCarousel = animalsDB.getAnimalsCarousel();
		initializeUI();
	}
	
	private void initializeUI()
	{

		gameCurrentAnimalImageView.setImageResource(animalsCarousel.get(currentIndex).getImageFile());
		MiscFunctions.initButtonStrings(currentIndex, animalsCarousel, gameChoice1Button, gameChoice2Button, gameChoice3Button);
	}

	public void onClick(View v) {
		
		Button clicked = (Button)v;
		if (clicked.getText().equals(animalsCarousel.get(currentIndex).getName()))
		{
			fromgoodanswer = true;
			MediaPlayer mediaPlayer = MediaPlayer.create(this, animalsCarousel.get(currentIndex).getSoundFile_e());
			mediaPlayer.setOnCompletionListener(this);
			mediaPlayer.start();
			
		}
		else
		{
			fromgoodanswer = false;
			MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.mauvaisereponse);
			mediaPlayer.setOnCompletionListener(this);
			mediaPlayer.start();
		}
		gameChoice1Button.setEnabled(false);
		gameChoice2Button.setEnabled(false);
		gameChoice3Button.setEnabled(false);
	}

	public void onCompletion(MediaPlayer arg0) {
		if (fromgoodanswer)
		{
			currentIndex++;
			if (currentIndex == animalsCarousel.size()) finish();
			else initializeUI();
		}
		gameChoice1Button.setEnabled(true);
		gameChoice2Button.setEnabled(true);
		gameChoice3Button.setEnabled(true);

		
	}
	
	
}
